import { Component, OnInit, SimpleChanges } from '@angular/core';
import { TagData } from "../../../entity/tag-data.model";
import { List } from 'linqts';
import { Farm } from "../../../entity/farm.model";
import { WindPowerLoad } from "./wind-power-load";
import { DatePipe } from "@angular/common";
import { DataSourceService } from "../../../service/data-source/data-source.service";
import { ApplicationService } from "../../../service/application.service";
import { FarmCategoryEnum } from '../../common/device-tag-selector/farm-category.enum';
import { DeviceCategoryEnum } from '../../common/device-tag-selector/device-category.enum';
import { Device } from "../../../entity/device.model";
import { NzMessageService } from 'ng-zorro-antd';

@Component({
	selector: 'app-wind-power-compare',
	templateUrl: './wind-power-compare.component.html',
	styleUrls: ['./wind-power-compare.component.css'],
	providers: [DataSourceService]
})
export class WindPowerCompareComponent implements OnInit {
	public farmCategory: FarmCategoryEnum = FarmCategoryEnum.winfarm;
	public deviceCategory: DeviceCategoryEnum[] = [DeviceCategoryEnum.turbine];
	/**
	 * 当前选中下标
	 * 
	 * @type {number}@memberof PowerCompareComponent
	 */
	active: number = 0;

	//查询时间
	serchTime: Date = new Date();

	//公司名称
	public titleCompany: string;

	//查询间隔时间
	private historyInterval: number = 15 * 60;    //1800秒

	/**
	 * 实时数据点集合
	 * 
	 * @private
	 * @type {TagValue[]}
	 * @memberof TurbineListComponent
	 */
	private tagDatas: TagData[] = [];

	/**
    * 风机对象集合
    * 
    * @type {limitedTurbine[]}@memberof TurbineTrendComponent
    */
	private devices: Device[];

	/**
     * 风场负荷模型
     * 
     * @type {LimitedFarm[]}
     * @memberof FarmEchartsComponent
     */
	public limitedFarmsLoads: WindPowerLoad[] = [];
	public copmanyFarmsLoads: companyFarmLoad;

	/**
     * 风机负荷模型
     * 
     * @type {LimitedFarm[]}
     * @memberof FarmEchartsComponent
     */
	public limitedTurbineLoads: WindPowerLoad[] = [];

    /**
     * 风场集合
     * 
     * @type {Farm[]}
     * @memberof FarmEchartsComponent
     */
	public farms: Farm[] = [];
	/**
   *设备选择最大数量
   *
   * @type {number}
   * @memberof FarmEchartsComponent
   */
	deviceCountLimit = 5;
	/**
	 *日期格式化
	 *
	 * @type {*}
	 * @memberof WindPowerCompareComponent
	 */
	en: any;
	constructor(
		private dataSource: DataSourceService,
		private application: ApplicationService,
		private datePipe: DatePipe,
		private _message: NzMessageService
	) {
		// this.titleCompany = this.application.currentCompany.companyName;
		this.titleCompany = '公司';
	}

	ngOnInit() {
		this.en = {
			firstDayOfWeek: 0,
			dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
			dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
			dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
			monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
			monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
			today: '今天',
			clear: '清除'
		};
		if (this.application.currentMenuParams && this.application.currentMenuParams['deviceCountLimit']) {
			this.deviceCountLimit = Number(this.application.currentMenuParams['deviceCountLimit'].paramValue);
		} else {
			this.deviceCountLimit = 5;
		}
		this.initData(this.active);
	}

	public onSelectedDevicesChange(ev: Device[]) {
		this.devices = ev;
	}

	public onClickHeader(n: number) {
		this.active = n;
		this.initData(this.active);
	}

	public onSearch() {
		if (this.devices.length > 20) {
			alert('最多选择20个风机！')
			return;
		}
		if (this.devices.length < 1) {
			alert('请选择风机！')
			return;
		}
		this.initData(this.active);
	}

	public ngOnDestroy(): void {
		this.dataSource.dispose();
	}

	private initData(active: number) {
		if (active == 0) {
			this.farms = this.application.currentUserFarms.filter(farm => farm.farmCategory == "winfarm")
			this.createLimitedFarm([...this.farms]);

		} else {
			if (this.devices != null)
				this.createLimitedTurbine(this.devices);
		}
	}

	createLimitedFarm(farms: Farm[]) {
		if (farms != null && farms.length > 0) {
			this.limitedFarmsLoads = [];
			let historyCodes: string[] = [];
			let WindSpeed = this.application.tagDict["MeanWindSpeed"];            // 平均风速
			let Power = this.application.tagDict["Power"];                       // 功率

			farms.forEach(farm => {
				//创建数据模型
				let limitedFarmLoad = {
					farmId: farm.farmId,
					farmCode: farm.farmCode,
					farmName: farm.farmName,

					meanWindSpeedBinging: this.dataSource.binding([farm.farmCode], WindSpeed),
					meanWindSpeeds: [],

					powerBinging: this.dataSource.binding([farm.farmCode], Power),
					powers: [],

					time: this.serchTime,
				}

				this.limitedFarmsLoads.push(limitedFarmLoad)   // 初始化数据	

			});

			this.copmanyFarmsLoads = {
				meanWindSpeeds: [],
				powers: [],
				companyName: this.titleCompany,
				time: this.serchTime,
			}

			historyCodes.push(...this.limitedFarmsLoads.map(o => o.meanWindSpeedBinging.code));
			historyCodes.push(...this.limitedFarmsLoads.map(o => o.powerBinging.code));

			//查询历史数据
			let start: Date = new Date(this.serchTime.getFullYear(), this.serchTime.getMonth(), this.serchTime.getDate());
			let end: Date = new Date(this.serchTime.getFullYear(), this.serchTime.getMonth(), this.serchTime.getDate() + 1);;

			this.dataSource.history
				.getHistories(historyCodes, start, end, this.historyInterval)
				.then(res => {
					if (res.length && res.length > 0) {
						this.getYesterday(res, start, end);
					}
				})
				.catch(error => {
					if (this.application.appConfigData.isShowErr) {
						this._message.info('获取风场测点历史数据' + error, { nzDuration: 3000 });
					}
					console.log(error);
				});
		}

	}

	private getYesterday(res: TagData[], startTime: Date, endTime: Date) {

		this.limitedFarmsLoads.forEach(farm => {
			let yesterdayWindSpeeds: any[] = [];  //风速
			let yesterdayPowers: any[] = [];      //功率

			let farmYesterdayWindSpeeds = res.filter(o => o.code === farm.meanWindSpeedBinging.code);
			let farmYesterdayPowers = res.filter(o => o.code === farm.powerBinging.code);

			if (farmYesterdayWindSpeeds && farmYesterdayWindSpeeds.length) {
				farmYesterdayWindSpeeds.forEach(yestWindSpeed => {
					let time: Date = this.parserDate(yestWindSpeed.time)
					yesterdayWindSpeeds.push([time, yestWindSpeed.value.toFixed(2)])
				});
				farm.meanWindSpeeds = yesterdayWindSpeeds;
			};

			if (farmYesterdayPowers && farmYesterdayPowers.length) {
				farmYesterdayPowers.forEach(yestPowers => {
					let time: Date = this.parserDate(yestPowers.time)
					yesterdayPowers.push([time, (yestPowers.value).toFixed(2)])
				});
				farm.powers = yesterdayPowers;
			};
		});

		this.copmanyFarmsLoads = null;
		let yesterdayWindSpeedDatas: any[] = [];
		let yesterdayPowerDatas: any[] = [];
		let companyMeanWindSpeeds: any[] = []
		let companyPowers: any[] = []
		this.limitedFarmsLoads.map(o => yesterdayWindSpeedDatas = yesterdayWindSpeedDatas.concat(o.meanWindSpeeds));
		this.limitedFarmsLoads.map(o => yesterdayPowerDatas = yesterdayPowerDatas.concat(o.powers));
		for (let time = startTime; time < endTime; time = new Date(time.getTime() + this.historyInterval * 1000)) {
			// 公司风速平均值；
			let total: number = 0;
			let windspeeds = yesterdayWindSpeedDatas.filter(o => o[0].getTime() === time.getTime());

			if (windspeeds.length) {
				windspeeds.map(o => total += o[1] * 1);
				let companyMeanWindSpeed = total / this.limitedFarmsLoads.length;
				companyMeanWindSpeeds.push([time, companyMeanWindSpeed.toFixed(2)]);
			}
			// 公司昨日功率合计；
			let totalPower: number = 0;
			let talPowers = yesterdayPowerDatas.filter(o => o[0].getTime() === time.getTime());
			if (talPowers.length) {
				talPowers.map(o => totalPower += o[1] * 1)
				companyPowers.push([time, (totalPower).toFixed(2)]);
			}
		}

		let companyFarmLoad: companyFarmLoad = {
			meanWindSpeeds: companyMeanWindSpeeds,
			powers: companyPowers,
			companyName: this.titleCompany,
			time: this.serchTime,
		}

		this.copmanyFarmsLoads = companyFarmLoad;

		// console.log(this.copmanyFarmsLoads)
	}

	createLimitedTurbine(turbines: Device[]) {

		if (turbines != null && turbines.length > 0) {
			this.limitedTurbineLoads = [];
			let historyCodes: string[] = [];
			let WindSpeed = this.application.tagDict["WindSpeed"];            //平均风速
			let Power = this.application.tagDict["ActivePower"];              //功率

			turbines.forEach(device => {
				//创建数据模型
				let limitedTurbineLoad = {
					deviceId: device.deviceId,
					deviceCode: device.deviceCode,
					deviceName: device.deviceName,

					meanWindSpeedBinging: this.dataSource.binding([device.farmCode, device.deviceCode], WindSpeed),
					meanWindSpeeds: [],

					powerBinging: this.dataSource.binding([device.farmCode, device.deviceCode], Power),
					powers: [],

					time: this.serchTime,
				}
				this.limitedTurbineLoads.push(limitedTurbineLoad)   // 初始化数据

			});

			historyCodes.push(...this.limitedTurbineLoads.map(o => o.meanWindSpeedBinging.code));
			historyCodes.push(...this.limitedTurbineLoads.map(o => o.powerBinging.code));

			//查询历史数据
			let start: Date = new Date(this.serchTime.getFullYear(), this.serchTime.getMonth(), this.serchTime.getDate());
			let end: Date = new Date(this.serchTime.getFullYear(), this.serchTime.getMonth(), this.serchTime.getDate() + 1);

			this.dataSource.history
				.getHistories(historyCodes, start, end, this.historyInterval)
				.then(res => {
					if (res.length && res.length > 0) {     // 如果数据返回为空不执行；
						this.getTurbineYesterday(res);
					}
				})
				.catch(error => {
					if (this.application.appConfigData.isShowErr) {
						this._message.info('获取风机测点历史数据' + error, { nzDuration: 3000 });
					};
					console.log(error);
				});

		}

	}

	private getTurbineYesterday(res: TagData[]) {
		this.limitedTurbineLoads.forEach(turbine => {
			let yesterdayWindSpeeds: any[] = [];  // 风速
			let yesterdayPowers: any[] = [];      // 功率

			let farmYesterdayWindSpeeds = res.filter(o => o.code === turbine.meanWindSpeedBinging.code);
			let farmYesterdayPowers = res.filter(o => o.code === turbine.powerBinging.code);

			if (farmYesterdayWindSpeeds && farmYesterdayWindSpeeds.length) {
				farmYesterdayWindSpeeds.forEach(yestWindSpeed => {
					let time: Date = this.parserDate(yestWindSpeed.time)
					yesterdayWindSpeeds.push([time, yestWindSpeed.value.toFixed(2)])
				});
				turbine.meanWindSpeeds = yesterdayWindSpeeds;
			};

			if (farmYesterdayPowers && farmYesterdayPowers.length) {
				farmYesterdayPowers.forEach(yestPowers => {
					let time: Date = this.parserDate(yestPowers.time)
					yesterdayPowers.push([time, yestPowers.value.toFixed(2)])
				});
				turbine.powers = yesterdayPowers;
			};
		});

	}

	private parserDate(date) {    //转化为标准日期格式；
		let t = Date.parse(date);
		if (!isNaN(t)) {
			return new Date(Date.parse(date.replace(/-/g, "/")));
		} else {
			return new Date();
		}
	};

}

interface companyFarmLoad {
	meanWindSpeeds: any[];
	powers: any[];
	companyName: string;
	time: Date;
}



// WEBPACK FOOTER //
// ./src/app/module/performance/wind-power-compare/wind-power-compare.component.ts